function _get_user_permissions(options) {
    Drupal.services.call({
        service: 'drupalgap_user',
        method: 'POST',
        resource: 'permissions',
        path: 'drupalgap_user/permissions.json',
        success: function (result) {
            try {
                if (options.success) {
                    options.success(result);
                }
            }
            catch (error) {
                if (options.error) {
                    options.error("", "", "_get_user_permissions error!");
                }
                console.log('_get_user_permissions - success - ' + error);
            }
        },
        error: function (request, status, message) {
            if (options.error) {
                options.error(request, status, message);
            }
        }
    });
}
function _user_has_role(role_name, user){
    for(var rid in user.roles){
        if(user.roles[rid] === role_name){
            return true;
        }
    }
    return false;
}
function _user_is_employee(user){
    if(_user_has_role("administrator",user)||_user_has_role("销售员",user)||_user_has_role("销售管理员",user)||_user_has_role("农化服务员",user)||_user_has_role("农化管理员",user)||_user_has_role("公司领导",user)){
        return true;
    }
    return false;
}
function _user_is_only_authenticated(user){
    var i = 0;
    var isAuthenticated = false;
    for(var rid in user.roles){
        i++;
        if(user.roles[rid] === "authenticated user"){
            isAuthenticated = true;
        }
    }
    if(isAuthenticated&&(i===1)){
        return true;
    }
    return false;
}
function str_trim(str){ //删除左右两端的空格
    return str.replace(/(^\s*)|(\s*$)/g, "");
}
function userInit(rootScope, waitIcon, state, timeout) {
    rootScope.user = {};
    var t = timeout(function () {
        if (!empty(waitIcon)) waitIcon.hide();
        state.go('error');
    }, 5000);
    system_connect({
        success: function (result) {
            if (result.user.uid == 0) {
                rootScope.user.uid = result.user.uid;
                rootScope.user.roles = result.user.roles;
                rootScope.user.permissions = [];
            } else {
                rootScope.user.uid = result.user.uid;
                rootScope.user.name = result.user.name;

                rootScope.user.roles = result.user.roles;
                rootScope.user.picture = null;
                user_load(result.user.uid, {
                    success:function(account) {
                        console.log(account);
                        if(!empty(account.picture) && !empty(account.picture.url)){
                            rootScope.user.picture = account.picture.url;
                        }else{
                            rootScope.user.picture=rootScope.picture_default;
                        }
                        if(!empty(account.field_cell)){
                            rootScope.user.cell = account.field_cell.und[0].value;
                        }
                        if(!empty(account.farmer_name)){
                            rootScope.user.farmer_name= account.farmer_name;
                        }

                    }
                });
                _get_user_permissions({
                    success:function(result) {
                        rootScope.user.permissions = result;
                        rootScope.$broadcast('get_permission', '');
                    }
                });
            }
            if (!empty(waitIcon)) waitIcon.hide();
            timeout.cancel(t);
            state.go('tabs.main');
        },
        error: function (xhr, status, message) {
            if (!empty(waitIcon)) waitIcon.hide();
            timeout.cancel(t);
            state.go('error');
        }
    });
}

function listCtrl(scope, rootScope,idName,listName, resourceName, ionicSideMenuDelegate) {
    scope.showDelete = false;
    scope.updateFilter();
    scope.toggleRight = function () {
        ionicSideMenuDelegate.toggleRight();
    };
    scope.toggleDelete = function () {
        scope.showDelete = !scope.showDelete;
    };
    scope.filterList = function () {
        scope.updateFilter();
        scope.reloadList();
        scope.toggleRight();
    };
    scope.initList = function () {
        rootScope[listName] = {};
        scope.listEnd = false;
        scope.latest = "";
        scope.oldest = "";
    };
    scope.reloadList = function () {
        scope.initList();
        scope.loadList();
    };
    scope.loadList = function (refresh) {
        var path_to_view = 'mobile_service_resources/' + resourceName;
        var cursor = "";
        var comparator = "";
        if(refresh) {
            //getting latest comments
            if (scope.latest != '') {
                comparator = '>';
                cursor = scope.latest;
            }
        } else {
            //loading old comments
            if (scope.oldest != '') {
                comparator = '<';
                cursor = scope.oldest;
            }
        }
        var params = scope.filterParams;
        params['cursor'] = cursor;
        params['comparator'] = comparator;
        _get_datasouce_result({
            path: path_to_view,
            param: params,
            resource:resourceName,
            success: function (data) {
                var length = data.data.length;
                if (data.data && data.data.length > 0) {
                    console.log(data);
                    for (var i=0; i<length; i++) {
                        var id = data.data[i][idName];
                        rootScope[listName][id] = {};
                        rootScope[listName][id][idName] = id;
                        for (var field in data.data[i]) {
                            if(data.data[i][field] == null){
                                data.data[i][field] = "";
                            }
                            rootScope[listName][id][field] = data.data[i][field];
                        }
                    }
                    if (!refresh) {
                        //如果上拉加载需要将时间戳下线设为本次数据最旧的时间
                        scope.oldest = data.data[length-1][idName];
                    }
                    if (refresh && data.data[length-1][idName] > scope.latest) {
                        //如果下拉刷新且最旧的数据的时间戳都比目前上限要新
                        scope.oldest = data.data[length-1][idName];
                        scope.listEnd = false;
                    }
                    if (refresh || scope.latest == '') {
                        //如果下拉刷新需要重置最新时间
                        scope.latest = data.data[0][idName];
                    }
                }
                if (!refresh && length < 10) {
                    scope.listEnd = true;
                }
                scope.$apply();
                if (refresh) {
                    scope.$broadcast('scroll.refreshComplete');
                } else {
                    scope.$broadcast('scroll.infiniteScrollComplete');
                }
            },
            error: function (request, status, message) {
                alert("网络错误" + message);
                scope.listEnd = true;
                if (refresh) {
                    scope.$broadcast('scroll.refreshComplete');
                } else {
                    scope.$broadcast('scroll.infiniteScrollComplete');
                }
            }
        });

    };
    scope.initList();
    scope.onItemDelete = function(item){
        delete_info(item[idName],idName,scope.moduleName,scope,rootScope,listName,idName,item);
    }
}

function articleListCtrl(scope, ionicLoading, rootScope,nodeType,listName) {

    scope.initList = function () {
        rootScope[listName] = {};
        scope.list = rootScope[listName];
        scope.listName = listName;
        scope.nodeType = nodeType;
        scope.listEnd = false;
        scope.latest = "";
        scope.oldest = "";
    };

    scope.reloadList = function () {
        scope.initList();
        scope.loadList();
    };

    scope.loadList = function (refresh) {
        var path_to_view = 'app-article-list/' + nodeType;
        if(refresh) {
            //getting latest comments
            if (scope.latest != '') {
                path_to_view = path_to_view + '/' + scope.latest + "--" + rootScope.newlimit;
            }
        } else {
            //loading old comments
            if (scope.oldest != '') {
                path_to_view = path_to_view + '/' + rootScope.oldlimit + "--" + scope.oldest;
            }
        }

        views_datasource_get_view_result(path_to_view, {
            success: function (data) {
                var length = data.nodes.length;
                if (length != 0) {
                    console.log(data);
                    for (var i=0; i<length; i++) {
                        var nid = data.nodes[i].node.nid;
                        rootScope[listName][nid] = {
                            nid: nid,
                            title: data.nodes[i].node.title,
                            body: data.nodes[i].node.body,
                            summary: data.nodes[i].node.summary,
                            time: data.nodes[i].node.time,
                            typeName: data.nodes[i].node.typeName,
                            typeId: data.nodes[i].node.typeId
                        };
                        if (data.nodes[i].node.img) {
                            rootScope[listName][nid].img = data.nodes[i].node.img.src;
                        } else {
                            //to-do: add default article pic
                        }
                    }
                    if (!refresh) {
                        //如果上拉加载需要将时间戳下线设为本次数据最旧的时间
                        scope.oldest = data.nodes[length - 1].node.nid;
                    }
                    if (refresh && data.nodes[length - 1].node.nid > scope.latest) {
                        //如果下拉刷新且最旧的数据的时间戳都比目前上限要新
                        scope.oldest = data.nodes[length - 1].node.nid;
                        scope.listEnd = false;
                    }
                    if (refresh || scope.latest == '') {
                        //如果下拉刷新需要重置最新时间
                        scope.latest = data.nodes[0].node.nid;
                    }
                }
                if (!refresh && length < 10) {
                    scope.listEnd = true;
                }
                scope.$apply();
                if (refresh) {
                    scope.$broadcast('scroll.refreshComplete');
                } else {
                    scope.$broadcast('scroll.infiniteScrollComplete');
                }
            }
        });
    };
    scope.initList();
}
function chooseFarmerCtrl(scope,rootScope,ionicSideMenuDelegate){
    scope.farmerAddressOption = {
        province: '',
        city: '',
        county: '',
        town: '',
        village: '',
        level:5
    };
    var farmer_name = '';
    var farmer_id = '';
    var is_farmer = false;
    var menu_toggle = "right";
    if(!empty(scope.id)){
        farmer_name = scope.detail.farmer_name;
        farmer_id = scope.detail.farmer_id;
        if(_user_has_role("农户",rootScope.user)){
            is_farmer = true;
            menu_toggle = '';
        }
    }else if(_user_has_role("农户",rootScope.user)){
        is_farmer = true;
        menu_toggle = '';
        farmer_name = rootScope.user.farmer_name;
        farmer_id = rootScope.user.uid;
    }
    scope.farmerInfo={
        farmer_name:'',
        cell:'',
        farmer_id:farmer_id,
        selected_farmer:farmer_name,
        is_farmer:is_farmer,
        menu_toggle:menu_toggle
    };
    scope.setFarmer = function(farmer_id,farmer_info){
        scope.farmerInfo.farmer_id=farmer_id;
        scope.farmerInfo.selected_farmer=farmer_info;
    }
    scope.filterFarmer = function(){
        scope.updateFilter();
        rootScope.chooseFarmerList = {};
        scope.listEnd = false;
        scope.latest = "";
        scope.oldest = "";
        scope.loadList();
    }
    scope.updateFilter = function() {
        scope.filterParams =
        {
            province: scope.farmerAddressOption.province,
            city: scope.farmerAddressOption.city,
            county: scope.farmerAddressOption.county,
            town: scope.farmerAddressOption.town,
            village: scope.farmerAddressOption.village,
            farmer_name:scope.farmerInfo.farmer_name,
            cell:scope.farmerInfo.cell
        };
    };
    listCtrl(scope, rootScope,"farmer_id","chooseFarmerList", "farmer_list", ionicSideMenuDelegate);
}

function sub_fertilizer_info($scope,$ionicPopover,tableName,field){
    $scope.subFertilizerOption={
        value:'',
        params:
        {
            action: "get_sacfvariety" //'plant','fertilizer','product','brand','sales_type','department_employee'
        },
        label:'化肥',
    };
    $scope.subDateOption={
        year:'',
        month:'',
        day:'',
        level:3
    };
    $scope.fertilizerInfo={
        type:'基肥',
        fertilizer_quantity:'',
    }
    $scope.onItemDelete = function(item,index,tableName){
        fertilizer_delete_info(item.id,'id',tableName,$scope,index);
    }
    // .fromTemplateUrl() 方法
    $ionicPopover.fromTemplateUrl('templates/system-templates/fertilizer.html', {
        scope: $scope
    }).then(function(popover) {
        $scope.popover = popover;
    });
    $scope.openFertilizerPopover = function($event) {
        $scope.popover.show($event);
    };
    $scope.closePopover = function() {
        $scope.popover.hide();
    };
    // 清除浮动框
    $scope.$on('$destroy', function() {
        $scope.popover.remove();
    });
    // 在隐藏浮动框后执行
    $scope.$on('popover.hidden', function() {
        // 执行代码
    });
    // 移除浮动框后执行
    $scope.$on('popover.removed', function() {
        // 执行代码
    });
    $scope.subFertilizerList=[];
    if (!empty($scope.id)) {
        var path_to_brand = 'mobile_service_resources/select_data_info';
        _get_datasouce_result({
            path: path_to_brand,
            param: {
                action: 'get_fertilizer_recomment',
                tableName: tableName,
                field: field,
                id: $scope.id,
            },
            resource: "select_data_info",
            success: function (data) {

                if (data) {
                    var length = data.length;
                    for (var index = 0; index < length; index++) {
                        var fertilizer = {
                            id: data[index].id,
                            type: data[index].type,
                            fertilizer_id: data[index].fertilizer_id,
                            fertilizer_name: data[index].variety_name + data[index].proportion + data[index].SM,
                            fertilizer_quantity: data[index].fertilizer_quantity,
                            fertilization_date: data[index].fertilization_date,
                            fertilization_method: data[index].fertilization_method,
                        };
                        $scope.subFertilizerList.push(fertilizer);
                    }
                    $scope.$apply();
                }
            }
        });
    }

    $scope.fertilizerSubmitForm = function () {
        var fertilizer_name = "";
        for(item in $scope.subFertilizerOption.optionSource){
            if($scope.subFertilizerOption.optionSource[item].id==$scope.subFertilizerOption.value){
                fertilizer_name = $scope.subFertilizerOption.optionSource[item].label;
            }
        }
        var fertilizer={
            type:$scope.fertilizerInfo.type,
            fertilizer_id:$scope.subFertilizerOption.value,
            fertilizer_name:fertilizer_name,
            fertilizer_quantity:$scope.fertilizerInfo.fertilizer_quantity,
            fertilization_date:$scope.subDateOption.year+'-'+$scope.subDateOption.month+'-'+$scope.subDateOption.day,
            fertilization_method:$scope.fertilizerInfo.fertilization_method,
        }
        $scope.subFertilizerList.push(fertilizer);
        $scope.closePopover();
    }
}

function getTags(tags) {
    var filtered_tags = [];
    var tags_array = tags.split(",");
    for(var index in tags_array){
        var tag = tags_array[index];
        var tag_array = tag.split("|");
        filtered_tags.push({
            tagName:tag_array[1],
            tagID : tag_array[0]
        });
    }
    return filtered_tags;
}

function expert_index(query, options) {
    try {
        services_resource_defaults(options, 'expert', 'index');
        entity_index('expert', query, options);
    }
    catch (error) {
        console.log('expert_index - ' + error);
    }
}

function _rest_service_resources(options) {
    try {
        if (options.param != null) {
            my_param = JSON.stringify(options.param);
        } else {
            my_param = null;
        }
        Drupal.services.call({
            service: 'rest',
            method: options.method,
            data: my_param,
            async: typeof options.async == 'boolean' ? options.async : true,
            path: options.path,
            success: function (result) {
                try {
                    if (options.success) {
                        options.success(result);
                    }
                }
                catch (error) {
                    console.log(
                        '_rest_sevice_resources - success - ' + error
                    );
                }
            }
        });
    }
    catch (error) {
        console.log('_rest_sevice_resources - ' + error);
    }
}
//得到view json 数据
function views_datasource_get_view_result(path, options) {
    try {
        // Since we do not use clean URLs, replace any potential question marks from
        // the path with an ampersand so the path will not be invalid.
        if (path.indexOf('?') != -1) {
            var replacement = path.replace('?', '&');
            path = replacement;
        }
        // If local storage caching is enabled, let's see if we can load the results
        // from there. If we successfully loaded the result, make sure it didn't
        // expire. If it did expire, remove it from local storage. If we don't have
        // it in local storage, or local storage caching is disabled, call Drupal to
        // get the results. After the results are fetched, save them to local
        // storage with an expiration time, if necessary. We use the path of the
        // view as the local storage key.
        // If we are resetting, remove the item from localStorage.
        if (options.reset) { window.localStorage.removeItem(path); }
        else if (Drupal.settings.cache.views.enabled) {
            var result = window.localStorage.getItem(path);
            if (result) {
                // Loaded from local storage, did it expire?
                result = JSON.parse(result);
                if (typeof result.expiration !== 'undefined' &&
                    result.expiration != 0 &&
                    time() > result.expiration
                ) {
                    // Expired, remove from local storage.
                    window.localStorage.removeItem(path);
                }
                else if (options.success) {
                    // Did not expire yet, use it.
                    options.success(result);
                    return;
                }
            }
        }
        Drupal.services.call({
            endpoint: '',
            service: 'views_datasource',
            resource: '',
            method: 'GET',
            path: path,
            success: function(result) {
                try {
                    if (options.success) {
                        // Add the path to the result.
                        result.path = path;
                        // If any views caching is enabled, cache the results in local
                        // storage.
                        if (Drupal.settings.cache.views.enabled) {
                            var expiration =
                                time() + Drupal.settings.cache.views.expiration;
                            if (Drupal.settings.cache.views.expiration == 0) {
                                expiration = 0;
                            }
                            // Saving to local storage.
                            result.expiration = expiration;
                            window.localStorage.setItem(path, JSON.stringify(result));
                        }
                        options.success(result);
                    }
                }
                catch (error) {
                    console.log(
                        'views_datasource_get_view_result - success - ' + error
                    );
                }
            },
            error: function(xhr, status, message) {
                try {
                    if (options.error) { options.error(xhr, status, message); }
                }
                catch (error) {
                    console.log('views_datasource_get_view_result - error - ' + error);
                }
            }
        });
    }
    catch (error) { console.log('views_datasource_get_view_result - ' + error); }
}

function _get_datasouce_result(options) {
    try {
        if (options.param != null) {
            my_param = JSON.stringify(options.param);
        } else {
            my_param = null;
        }
        Drupal.services.call({
            service: 'mobile_service',
            method: 'POST',
            data: my_param,
            async :typeof options.async == 'boolean' ?options.async:true,
            path: options.path,
            success: function (result) {
                try {
                    if (options.success) {
                        //Add the path to the result.
                        result.path = options.path;
                        //If any views caching is enabled, cache the results in local storage.
                        if (Drupal.settings.cache.views.enabled) {
                            var expiration =
                                time() + Drupal.settings.cache.views.expiration;
                            if (Drupal.settings.cache.views.expiration == 0) {
                                expiration = 0;
                            }
                            //Saving to local storage.
                            result.expiration = expiration;
                            window.localStorage.setItem(path, JSON.stringify(result));
                        }
                        options.success(result);
                    }
                }
                catch (error) {
                    if (options.error) {
                        options.error("", "", "_get_datasouce_result error!");
                    }
                    console.log(
                        '_get_datasouce_result - success - ' + error
                    );
                }
            },
            error: function (request, status, message) {
                if (options.error) {
                    options.error(request, status, message);
                }
            }
        });
    }
    catch (error) {
        console.log('my_module_get_retailstore - ' + error);
    }
}

function _get_address_id(addressOption) {
    var address = '';
    if (addressOption['village']!= "" && addressOption['village'] ) {
        address = addressOption['village'];
    } else if (addressOption['town'] && addressOption['town'] != "") {
        address = addressOption['town'];
    } else if (addressOption['county'] && addressOption['county'] != "" ) {
        address = addressOption['county'];
    } else if (addressOption['city'] && addressOption['city'] != "" ) {
        address = addressOption['city'];
    } else if (addressOption['province'] && addressOption['province'] != "" ) {
        address = addressOption['province'];
    }
    return address ;
}

function delete_info(Id,columnName,tableName,scope,rootScope,listName,idName,item){
    var path_to_view = 'mobile_service_resources/delete_info';
    var params = {
        id: Id,
        columnName: columnName,
        tableName: tableName
    };
    _get_datasouce_result({
        path: path_to_view,
        param: params,
        resource: "delete_info",
        success: function (data) {
            console.log(data);
            if(!data.success){
                alert("删除失败!");
            }else{
                delete rootScope[listName][item[idName]];
                scope.$apply();
            }
        }
    });
}
function fertilizer_delete_info(Id,columnName,tableName,scope,index){
    if(empty(Id)){
        scope.subFertilizerList.splice(index,1);
        return;
    }
    var path_to_view = 'mobile_service_resources/delete_info';
    var params = {
        id: Id,
        columnName: columnName,
        tableName: tableName
    };
    _get_datasouce_result({
        path: path_to_view,
        param: params,
        resource: "delete_info",
        success: function (data) {
            console.log(data);
            if(!data.success){
                alert("删除失败!");
            }else{
                scope.subFertilizerList.splice(index,1);
                scope.$apply();
            }
        }
    });
}

function get_year_month_day_from_date(date){
    var date_arr = date.split('-');
    var arr = [];
     arr['year'] = date_arr[0];
     arr['month'] = date_arr[1];
     arr['day'] = date_arr[2];
    return arr;
}

function get_select_name(source,id){
    var length = source.length;
    for(var i=0;i<length;i++) {
        if(source[i].id == id ){
            return source[i].label;
        }
    }
    return "";
}
function _drupalgap_empty_2_zero(data){
    return !empty(data) ? data : '0';
}

function _init_popover($scope,ionicPopover){
    ionicPopover.fromTemplateUrl('stats-popover.html', {
        scope: $scope
    }).then(function(popover) {
        $scope.popover = popover;
    });

    $scope.openPopover = function($event) {
        $scope.popover.show($event);

    };
    $scope.closePopover = function() {
        $scope.popover.hide();
    };
    // 清除浮动框
    $scope.$on('$destroy', function() {
        $scope.popover.remove();
    });
    // 在隐藏浮动框后执行
    $scope.$on('popover.hidden', function() {
        // 执行代码
    });
    // 移除浮动框后执行
    $scope.$on('popover.removed', function() {
        // 执行代码
    });
}

function detailCanEdited($rootScope,$scope){
    var access = false;
    if($rootScope.user_access("edit all " + $scope.moduleName)){
        access = true;
    }else if($rootScope.user_access("edit own " + $scope.moduleName) && ($scope.detail.author_uid == $rootScope.user.uid)){
        access = true;
    }
    return access;
}